package com.yans.managers
{ 
	
	import com.yans.interfaces.ILoaderManager;
	import com.yans.interfaces.ILoaderResult;
	import com.yans.managers.consts.LoaderType;
	import com.yans.managers.vo.LoaderResult;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	
	public class LoaderManager implements ILoaderManager
	{
		private var _call:Dictionary;
		private var _urls:Dictionary;
		
		private var _loader:Loader;
		private var _urlLoader:URLLoader;
		
		public function LoaderManager()
		{
			_call = new Dictionary;
			_urls = new Dictionary;
		}
		
		public function urlLoader(path:String, call:Function, dataFormat:String=URLLoaderDataFormat.BINARY):void {
			_urlLoader = new URLLoader;
			_urlLoader.dataFormat = dataFormat;
			_call[_urlLoader] = call;
			_urls[_urlLoader] = path;
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
			_urlLoader.addEventListener(Event.COMPLETE, onUrlLoaderCompleted);
			_urlLoader.load(new URLRequest(path));
		}
		
		private function onLoaderError(e:IOErrorEvent):void {
			var callback:Function = _call[e.target];
			callback(new LoaderResult(LoaderType.ERROR, _urls[e.target], e.text) as ILoaderResult);
		}
		
		private function onUrlLoaderCompleted(e:Event):void {
			var callback:Function = _call[e.target];
			callback(new LoaderResult(LoaderType.URLLOADER, _urls[e.target], e.target) as ILoaderResult); 
		}
		
		
		public function loader(path:String, call:Function):void {
			_loader = new Loader;
			_call[_loader.contentLoaderInfo] = call;
			_urls[_loader.contentLoaderInfo] = path;
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderCompleted);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError); 
			var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
			loaderContext.allowCodeImport = true;
			loaderContext.allowLoadBytesCodeExecution = true;
			_loader.load(new URLRequest(path), loaderContext);
		}
		
		private function onLoaderCompleted(e:Event):void {
			var callBack:Function = _call[e.target];
			callBack(new LoaderResult(LoaderType.LOADER, _urls[e.target], e.target) as ILoaderResult);
		}
	}
}